﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.AuditLogging.Client.Configuration;
using System.Configuration;
using PSE.Framework.Configuration;

///Configuracoes podem ser recuperadas tanto do config do executavel quanto atraves do componente ApplicationConfiguration
namespace PSE.AuditLogging.Client
{
    /// <summary>
    /// Classe que encapsula a leitura das configurações utilizadas pelo client
    /// </summary>
    public class ConfigurationReader
    {
        static object _syncRoot = new object();
        static LogSenderConfigurationSection _logClientConfiguration;

        public static LogSenderConfigurationSection LogClientConfiguration
        {
            get
            {
                lock (_syncRoot)
                {
                    //tentar recuperar a configuracao do arquivo de config do executavel
                    if (_logClientConfiguration == null)
                        _logClientConfiguration = System.Configuration.ConfigurationManager.GetSection("logSenderConfiguration") as LogSenderConfigurationSection;

                    //caso a configuracao nao exista no arquivo de configuracao da aplicacao
                    if (_logClientConfiguration == null)
                    {
                        //tentar recuperar a configuracao atraves do ApplicationConfiguration
                        ApplicationConfiguration appCondig = ApplicationConfiguration.GetCurrent();
                        if (appCondig != null)
                            _logClientConfiguration = appCondig.GetSection<LogSenderConfigurationSection>("logSenderConfiguration");
                    }

                    if (_logClientConfiguration == null)
                        throw new ConfigurationErrorsException("Configuration section 'logSenderConfiguration' not found in config file.");

                    return _logClientConfiguration;
                }
            }
            set
            {
                lock (_syncRoot)
                {
                    _logClientConfiguration = value;
                }
            }
        }

        public static void Refresh()
        {
            lock (_syncRoot)
            {
                //tentar recuperar a configuracao do arquivo de config do executavel
                System.Configuration.ConfigurationManager.RefreshSection("logSenderConfiguration");
                _logClientConfiguration = null;
            }
        }
    }
}
